package com.it.gw.modules.water.fragment

import LoginVo
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import com.didi.drouter.utils.TextUtils
import com.it.common.utils.DateUtils
import com.it.common.utils.DateUtils.DAY_DATE_FORMATTER
import com.it.common.utils.DialogUtils
import com.it.common.utils.isNotEmpty
import com.it.data.manager.AppCacheManager
import com.it.data.network.req.UpdateRsvrInfoDto
import com.it.data.network.rsp.RsvrVo
import com.it.gw.R
import com.it.gw.base.BaseFragment
import com.it.gw.databinding.DialogWheelViewBinding
import com.it.gw.databinding.FragmentReservoirUploadBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.modules.water.activity.ReservoirUploadActivity
import com.tencent.mmkv.MMKV
import java.util.Date


class ReservoirUploadFragment : BaseFragment<FragmentReservoirUploadBinding>() {


    companion object {
        const val TAG = "ReservoirUploadFragment"
    }

    override fun initObserver() {
        //水库列表
        (requireActivity() as ReservoirUploadActivity).waterViewModel.rsvrVoLiveData.observe(this) {
            ProgressDialog.hide()
            runCatching {
                rsvrVo =
                    (requireActivity() as ReservoirUploadActivity).waterViewModel.rsvrVoLiveData.value?.data?.get(
                        0
                    )
                binding.rvName.setText(rsvrVo?.stnm)
                stcd = rsvrVo?.stcd
                getRsvrByStcdAndTm_APP()
            }.onFailure {
                Toast.makeText(requireActivity(), "未查询到水库", Toast.LENGTH_SHORT).show()
            }
        }
        //水库列表
        (requireActivity() as ReservoirUploadActivity).waterViewModel.checkStateVoLiveData.observe(
            this
        ) {
            if (it.result && it.data != null && it?.data?.state == "1") {
                //已经审核
                binding.btnSave.isEnabled = false
                binding.btnSave.setBackgroundResource(R.drawable.shape_dark)
            } else {
                //未审核
                binding.btnSave.isEnabled = true
                binding.btnSave.setBackgroundResource(R.drawable.shape_btn)
            }
        }


        //水库填报数据
        (requireActivity() as ReservoirUploadActivity).waterViewModel.rsvrByStcdAndTmLiveData.observe(
            this
        ) {
            ProgressDialog.hide()
            clearInput();
            if (it.result) {
                if (it.data.isNotEmpty()) {
                    binding.date.text = it.data?.tm
                    stcd = it.data?.stcd
                    binding.rz.setText(it.data?.rz)
                    binding.w.setText(it.data?.w)
                    binding.inq.setText(it.data?.inq)
                    binding.otq.setText(it.data?.otq)
                    binding.sWater.setText(it.data?.s_water)
                    binding.remark.setText(it.data?.remark)
                }

            } else {
                Toast.makeText(context, it.msg, Toast.LENGTH_SHORT).show()
            }


        }

        (requireActivity() as ReservoirUploadActivity).waterViewModel.updateRsvrInfoLiveData.observe(
            this
        ) {
            ProgressDialog.hide()
            if (it.result) {
                Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show()
                getRsvrByStcdAndTm_APP()
//                //刷新水情详情
                (requireActivity() as ReservoirUploadActivity).reservoirSeeFragment.getRsvrByAddvcdAndTm_APP()
            } else {
                Toast.makeText(context, it.msg, Toast.LENGTH_SHORT).show()
            }


        }

    }

    private fun clearInput() {

        binding.rz.setText(null)
        binding.w.setText(null)
        binding.inq.setText(null)
        binding.otq.setText(null)
        binding.sWater.setText(null)
        binding.remark.setText(null)
    }

    @SuppressLint("RestrictedApi")
    override fun initListener() {
        binding.date.setOnClickListener {
            (requireActivity() as ReservoirUploadActivity).showDatePickerDialog(selectDateAction = {
                binding.date.text = it
                getRsvrByStcdAndTm_APP()
            })
        }
        binding.rvName.setOnClickListener {
            showMyReserWheelViewDialog { index ->
                runCatching {
                    rsvrVo =
                        (requireActivity() as ReservoirUploadActivity).waterViewModel.rsvrVoLiveData.value?.data?.get(
                            index
                        )
                    binding.rvName.setText(rsvrVo?.stnm)
                    stcd = rsvrVo?.stcd
                    getRsvrByStcdAndTm_APP()
                }.onFailure {
                    Toast.makeText(requireActivity(), "未查询到水库", Toast.LENGTH_SHORT).show()
                }
            }
        }
        binding.btnSave.setOnClickListener {
            if (TextUtils.isEmpty(binding.date.text.toString())) {
                Toast.makeText(requireActivity(), "请选择日期", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(binding.rvName.text.toString())) {
                Toast.makeText(requireActivity(), "请选择水库", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(binding.rz.text.toString())) {
                Toast.makeText(requireActivity(), "请输入当日水位", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            if (TextUtils.isEmpty(binding.w.text.toString())) {
                Toast.makeText(requireActivity(), "请输入当日库容", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            if (TextUtils.isEmpty(binding.inq.text.toString())) {
                Toast.makeText(requireActivity(), "请输入进库流量", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            var rz = binding.rz.text.toString()
            var w = binding.w.text.toString()
            var inq = binding.inq.text.toString()
            var otq = binding.otq.text.toString()


            if (rz.startsWith(".")) {
                rz = "0${rz}"
            }
            if (w.startsWith(".")) {
                w = "0${w}"
            }
            if (inq.startsWith(".")) {
                inq = "0${inq}"
            }
            if (otq.startsWith(".")) {
                otq = "0${otq}"
            }
            if ((rz.toDouble() == 0.0 || w.toDouble() == 0.0) && TextUtils.isEmpty(binding.remark.text.toString())) {
                inputDescTips(rz, w, inq, otq);

            } else {
                confirm(rz, w, inq, otq)
            }


        }

    }

    /**
     * 填写备注的对话框
     */
    private fun inputDescTips(rz: String, w: String, inq: String, otq: String) {
        val pwdDialog =
            DialogUtils.getDialogNotTouchOutside(requireActivity(), R.layout.dialog_common_tips2)
        pwdDialog.show()
        val tip = pwdDialog.findViewById<TextView>(R.id.tip)
        val content = pwdDialog.findViewById<TextView>(R.id.content)
        tip.text = "提示"
        content.text = "请详细描述数据为0的原因"
        val tvOK = pwdDialog.findViewById<TextView>(R.id.tv_ok)
        val tvCancel = pwdDialog.findViewById<TextView>(R.id.tv_cancel)

        tvOK.setOnClickListener {
            pwdDialog.dismiss()
        }
        tvCancel.setOnClickListener {
            pwdDialog.dismiss()
        }
    }

    override fun getView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentReservoirUploadBinding.inflate(layoutInflater)
        return binding.root
    }


    override fun initData() {
        val date = DateUtils.dateToString(DAY_DATE_FORMATTER, Date())
        val depId = MMKV.defaultMMKV()
            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)?.depId
        depId?.let {
            ProgressDialog.show(requireActivity())
            (requireActivity() as ReservoirUploadActivity).waterViewModel.selectUserManageRsvrList_APP(
                it
            )
        };
        binding.date.text = date


    }

    private var stcd: String? = "";

    //获取填写详情
    private fun getRsvrByStcdAndTm_APP() {
        ProgressDialog.show(requireActivity())
        (requireActivity() as ReservoirUploadActivity).waterViewModel.getRsvrByStcdAndTm_APP(
            binding.date.text.toString(),
            stcd!!
        )
        //查询审核状态
        getCheckStateByTm(stcd!!)
    }

    /**
     * 获取数据上报审核状态
     */
    fun getCheckStateByTm(stcd: String) {
//        val depId = MMKV.defaultMMKV()
//            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)?.depId
        (requireActivity() as ReservoirUploadActivity).waterViewModel.getCheckStateByTm(
            stcd = stcd,
            date = binding.date.text.toString()
        );

    }

    override fun initView() {

    }

    var rsvrVo: RsvrVo? = null

    //选择所管水库
    fun showMyReserWheelViewDialog(okAction: (Int) -> Unit) {
        val dialogWheelViewBinding = DialogWheelViewBinding.inflate(layoutInflater)
        val list =
            (requireActivity() as ReservoirUploadActivity).waterViewModel.rsvrVoLiveData.value?.data?.map { v -> v.stnm }
        dialogWheelViewBinding.loopView.setItems(list)
        val dialog =
            DialogUtils.getDialog(requireActivity(), dialogWheelViewBinding.root)
        dialogWheelViewBinding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogWheelViewBinding.tvOk.setOnClickListener {
            dialog.dismiss()
            val index = dialogWheelViewBinding.loopView.selectedItem
            okAction.invoke(index)

        }
        dialog.show()
    }

    private fun confirm(rz: String, w: String, inq: String, otq: String) {
        val pwdDialog =
            DialogUtils.getDialogNotTouchOutside(requireActivity(), R.layout.dialog_common_tips2)
        pwdDialog.show()
        val tip = pwdDialog.findViewById<TextView>(R.id.tip)
        val content = pwdDialog.findViewById<TextView>(R.id.content)
        tip.text = "提示"
        content.text = "请检查信息是否填写正确？"
        val tvOK = pwdDialog.findViewById<TextView>(R.id.tv_ok)
        val tvCancel = pwdDialog.findViewById<TextView>(R.id.tv_cancel)

        tvOK.setOnClickListener {
            pwdDialog.dismiss()
            val depId = MMKV.defaultMMKV()
                .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)?.depId
            val id = MMKV.defaultMMKV()
                .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)?.id

            val dro = UpdateRsvrInfoDto(
                dcode = depId,
                tm = binding.date.text.toString(),
                stcd = stcd, rz = rz,
                w = w,
                inq = inq,
                otq = otq,
                s_water = binding.sWater.text.toString(),
                remark = binding.remark.text.toString()
            )
            ProgressDialog.show(requireActivity())
            (requireActivity() as ReservoirUploadActivity).waterViewModel.updateRsvrInfo(dro)
        }
        tvCancel.setOnClickListener {
            pwdDialog.dismiss()
        }


    }


}